package simpledb;

import java.io.Serializable;
import java.util.*;

/**
 * TupleDesc describes the schema of a tuple.
 */
public class TupleDesc implements Serializable {

    /**
     * A help class to facilitate organizing the information of each field
     */
    public static class TDItem implements Serializable {

        private static final long serialVersionUID = 1L;

        /**
         * The type of the field
         */
        public final Type fieldType;

        /**
         * The name of the field
         */
        public final String fieldName;

        public TDItem(Type t, String n) {
            this.fieldName = n;
            this.fieldType = t;
        }

        @Override
        public String toString() {
            return fieldName + "(" + fieldType + ")";
        }
    }

    private ArrayList<TDItem> tdItemArrayList;

    /**
     * @return An iterator which iterates over all the field TDItems
     * that are included in this TupleDesc
     */
    public Iterator<TDItem> iterator() {
        // some code goes here
        return new Iterator<TDItem>() {
            private int cur = -1;

            @Override
            public boolean hasNext() {
                return cur != tdItemArrayList.size() - 1;
            }

            @Override
            public TDItem next() {
                cur++;
                return tdItemArrayList.get(cur);
            }
        };
    }

    private static final long serialVersionUID = 1L;

    /**
     * Create a new TupleDesc with typeAr. length fields with fields of the
     * specified types, with associated named fields.
     *
     * @param typeAr  array specifying the number of and types of fields in this
     *                TupleDesc. It must contain at least one entry.
     * @param fieldAr array specifying the names of the fields. Note that names may
     *                be null.
     */
    public TupleDesc(Type[] typeAr, String[] fieldAr) {
        // some code goes here
        tdItemArrayList = new ArrayList<>();
        for (int i = 0; i < typeAr.length; i++) {
            tdItemArrayList.add(new TDItem(typeAr[i], fieldAr[i]));
        }
    }

    /**
     * Constructor. Create a new tuple desc with typeAr.length fields with
     * fields of the specified types, with anonymous (unnamed) fields.
     *
     * @param typeAr array specifying the number of and types of fields in this
     *               TupleDesc. It must contain at least one entry.
     */
    public TupleDesc(Type[] typeAr) {
        // some code goes here
        tdItemArrayList = new ArrayList<>();
        for (int i = 0; i < typeAr.length; i++) {
            tdItemArrayList.add(new TDItem(typeAr[i], new String()));
        }
    }

    /**
     * @return the number of fields in this TupleDesc
     */
    public int numFields() {
        // some code goes here
        return tdItemArrayList.size();
    }

    /**
     * Gets the type of the ith field of this TupleDesc
     *
     * @param i index of the field name to return. It must be a valid index.
     * @return the name of the ith field
     * @throws NoSuchElementException if i is not a valid field reference.
     */
    public String getFieldName(int i) throws NoSuchElementException {
        // some code goes here
        return tdItemArrayList.get(i).fieldName;
    }

    /**
     * Gets the type of the ith field of this TupleDesc.
     *
     * @param i The index of the field to get the type of. It must be a valid
     *          index.
     * @return the type of the ith field
     * @throws NoSuchElementException if i is not a valid field reference.
     */
    public Type getFieldType(int i) throws NoSuchElementException {
        // some code goes here
        return tdItemArrayList.get(i).fieldType;
    }

    /**
     * Find the index of the field with a given name.
     *
     * @param name name of the field.
     * @return the index of the field that is first to have the given name.
     * @throws NoSuchElementException if no field with a matching name is found.
     */
    public int fieldNameToIndex(String name) throws NoSuchElementException {
        // some code goes here
        for (int i = 0; i < tdItemArrayList.size(); i++) {
            if (tdItemArrayList.get(i).fieldName.equals(name)) {
                return i;
            }
        }
        throw new NoSuchElementException();
    }

    /**
     * @return The size (in bytes) of tuples corresponding to this TupleDesc.
     * Note that tuples from a given TupleDesc are of a fixed size.
     */
    public int getSize() {
        // some code goes here
        int result=0;
        for (TDItem tdItem:
             tdItemArrayList) {
            result+=tdItem.fieldType.getLen();
        }
        return result;
    }

    /**
     * Merge two TupleDescs into one, with td1.numFields + td2.numFields fields,
     * with the first td1.numFields coming from td1 and the remaining from td2.
     *
     * @param td1 The TupleDesc with the first fields of the new TupleDesc
     * @param td2 The TupleDesc with the last fields of the TupleDesc
     * @return the new TupleDesc
     */
    public static TupleDesc merge(TupleDesc td1, TupleDesc td2) {
        // some code goes here
        int numFields1 = td1.numFields();
        int numFields2 = td2.numFields();
        int numFields = numFields1 + numFields2;
        Type[] typeAr = new Type[numFields];
        String[] fieldAr = new String[numFields];
        for (int i = 0; i < numFields1; i++) {
            int idx = i;
            typeAr[idx] = td1.getFieldType(idx);
            fieldAr[idx] = new String(td1.getFieldName(idx));
        }
        for (int i = 0; i < numFields2; i++) {
            int idx = i + numFields1;
            typeAr[idx] = td2.getFieldType(i);
            fieldAr[idx] = new String(td2.getFieldName(i));
        }
        return new TupleDesc(typeAr, fieldAr);
    }

    /**
     * Compares the specified object with this TupleDesc for equality. Two
     * TupleDescs are considered equal if they have the same number of items
     * and if the i-th type in this TupleDesc is equal to the i-th type in o
     * for every i.
     *
     * @param o the Object to be compared for equality with this TupleDesc.
     * @return true if the object is equal to this TupleDesc.
     */

    @Override
    public boolean equals(Object o) {
        // some code goes here
        if (o == this) {
            return true;
        }
        if (o instanceof TupleDesc) {
            TupleDesc tupleDesc = (TupleDesc) o;
            if (this.tdItemArrayList.size() != tupleDesc.tdItemArrayList.size()) {
                return false;
            } else {
                for (int i = 0; i < this.tdItemArrayList.size(); i++) {
                    if (this.tdItemArrayList.get(i).equals(tupleDesc.tdItemArrayList.get(i))) {
                        return false;
                    }
                }
                return true;
            }
        }
        return false;
    }

    @Override
    public int hashCode() {
        // If you want to use TupleDesc as keys for HashMap, implement this so
        // that equal objects have equals hashCode() results
//        throw new UnsupportedOperationException("unimplemented");
        int result = 0;
        for (TDItem tdItem :
                tdItemArrayList) {
            result = 13 * result % 0x07fffff + tdItem.hashCode() % 0x07ffffff;
        }
        return result;
    }

    /**
     * Returns a String describing this descriptor. It should be of the form
     * "fieldType[0](fieldName[0]), ..., fieldType[M](fieldName[M])", although
     * the exact format does not matter.
     *
     * @return String describing this descriptor.
     */
    @Override
    public String toString() {
        // some code goes here
        String tupleDescString = "";
        for (int i = 0; i < tdItemArrayList.size() - 1; i++) {
            String tdItemString = tdItemArrayList.get(i).toString() + ",";
            tupleDescString += tdItemString;
        }
        tupleDescString += tdItemArrayList.get(tdItemArrayList.size() - 1).toString();
        return tupleDescString;
    }
}
